package com.hw.one.dam2.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.*;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/04/13 16:25.
 */
public class HttpClientUtil {

    static Logger log = Logger.getLogger(HttpClientUtil.class);
    /**
     * http get 请求
     * @author 李亚坤
     * @createtime 2017年4月13日16:27:34
     * @param getUrl
     * @param getHeaders
     * @return
     * @throws IOException
     */
    public static Map<String, String> sendGet(String getUrl, Map<String, String> getHeaders) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("get请求:" + getUrl);
        try {
            // 根据地址获取请求
            HttpGet httpGet = new HttpGet(getUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for(String pKey : getHeaders.keySet()) {
                httpGet.setHeader(pKey, getHeaders.get(pKey));
            }
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpGet);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result= EntityUtils.toString(response.getEntity(),"utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        }catch (Exception e) {
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    /**
     * http get 请求
     * @author 李亚坤
     * @createtime 2017年4月13日16:27:34
     * @param getUrl
     * @param getHeaders
     * @return
     * @throws IOException
     */
    public static Map<String, String> sendGetWithParams(String getUrl, Map<String, String> getHeaders, Map<String, String> paramMap) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("get请求:" + getUrl);
        try {
            // 根据地址获取请求
            HttpGet httpGet = new HttpGet();

            // 设置请求头
            for(String pKey : getHeaders.keySet()) {
                httpGet.setHeader(pKey, getHeaders.get(pKey));
            }
            URIBuilder builder = new URIBuilder(getUrl);
            if (paramMap != null && !paramMap.isEmpty())
            {
                builder.setParameters(paramsConverter(paramMap));
            }
            httpGet.setURI(builder.build());
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpGet);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result= EntityUtils.toString(response.getEntity(),"utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        }catch (Exception e) {
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }



    private static List<NameValuePair> paramsConverter(Map<String, String> params) {
        List<NameValuePair> nvps = new LinkedList<NameValuePair>();
        Set<Map.Entry<String, String>> paramsSet = params.entrySet();
        for (Map.Entry<String, String> paramEntry : paramsSet) {
            nvps.add(new BasicNameValuePair(paramEntry.getKey(),
                    paramEntry.getValue()));
        }

        return nvps;
    }

    /**
     * http post 请求
     * @author 李亚坤
     * @createtime 2017年4月13日16:28:21
     * @param postUrl
     * @param postHeaders
     * @param postEntity
     * @return
     * @throws IOException
     */
    public static Map<String, String> sendPost(String postUrl,Map<String, String> postHeaders, Map<String, String> postEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("post请求:" + postUrl);
        try {
            // 根据地址获取请求
            HttpPost httpPost = new HttpPost(postUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for(String pKey : postHeaders.keySet()) {
                httpPost.setHeader(pKey, postHeaders.get(pKey));
            }
            // 拼接参数
            List <NameValuePair> nvps = new ArrayList<>();
            for(String pKey : postEntity.keySet()) {
                nvps.add(new BasicNameValuePair(pKey, postEntity.get(pKey)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result= EntityUtils.toString(response.getEntity(),"utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    public static Map<String, String> sendPostWithStr(String postUrl,Map<String, String> postHeaders, String postEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("post请求:" + postUrl);
        try {
            // 根据地址获取请求
            HttpPost httpPost = new HttpPost(postUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for(String pKey : postHeaders.keySet()) {
                httpPost.setHeader(pKey, postHeaders.get(pKey));
            }
            // 拼接参数
            httpPost.setEntity(new StringEntity(postEntity, ContentType.APPLICATION_JSON));
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result= EntityUtils.toString(response.getEntity(),"utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }
    /**
     * http put 请求
     * @author 李亚坤
     * @createtime 2017年4月13日16:28:51
     * @param putUrl
     * @param putHeaders
     * @param putEntity
     * @return
     * @throws Exception
     */
    public static Map<String, String> sendPut(String putUrl, Map<String, String> putHeaders, Map<String, String> putEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("put请求:" + putUrl);
        try {
            // 根据地址获取请求
            HttpPut httpPut = new HttpPut(putUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for(String pKey : putHeaders.keySet()) {
                httpPut.setHeader(pKey, putHeaders.get(pKey));
            }
            // 设置请求值
            List <NameValuePair> nvps = new ArrayList<>();
            for(String pKey : putEntity.keySet()) {
                nvps.add(new BasicNameValuePair(pKey, putEntity.get(pKey)));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(nvps));
            // 获取响应对象
            HttpResponse response = httpClient.execute(httpPut);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result= EntityUtils.toString(response.getEntity(),"utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        }catch (Exception e) {
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }


    public static void main(String[] args) {
        try {

            String getUrl = "http://service.envicloud.cn:8082/v2/air/live/device/AHDLBNZPY2XVDWQXNDY0NJU3OTA2NJIY/1938A";
            Map<String, String> response = sendGet(getUrl, new HashMap<>());

            for (String key : response.keySet()) {
                if ("result".equals(key)) {
                    JSONObject resultObj = JSONObject.parseObject(response.get("result"));
                    if ("Success".equals(resultObj.get("rdesc"))) {
                        JSONObject infoObj = resultObj.getJSONObject("info");
                        System.out.println("PM10 = " + infoObj.get("PM10"));
                        System.out.println("PM25 = " + infoObj.get("PM25"));
                        System.out.println("SO2 = " + infoObj.get("SO2"));
                        System.out.println("NO2 = " + infoObj.get("NO2"));
                        System.out.println("CO = " + infoObj.get("CO"));
                        System.out.println("o3 = " + infoObj.get("o3"));
                        System.out.println("AQI = " + infoObj.get("AQI"));
                        System.out.println("prkey = " + infoObj.get("prkey"));
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();

        }
    }



}